package vip.xiaonuo.supplier.modular.base.productions.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fhs.trans.service.impl.TransService;
import jakarta.annotation.Resource;
import org.json.JSONException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.supplier.modular.base.categories.entity.SupplierCategories;
import vip.xiaonuo.supplier.modular.base.categories.service.SupplierCategoriesService;
import vip.xiaonuo.supplier.modular.base.productions.entity.SupplierProductions;
import vip.xiaonuo.supplier.modular.base.productions.mapper.SupplierProductionsMapper;
import vip.xiaonuo.supplier.modular.base.productions.param.SupplierProductionsAddParam;
import vip.xiaonuo.supplier.modular.base.productions.param.SupplierProductionsEditParam;
import vip.xiaonuo.supplier.modular.base.productions.param.SupplierProductionsIdParam;
import vip.xiaonuo.supplier.modular.base.productions.param.SupplierProductionsPageParam;
import vip.xiaonuo.supplier.modular.base.productions.service.SupplierProductionsService;
import vip.xiaonuo.supplier.modular.warehouse.stocks.entity.SupplierStocks;
import vip.xiaonuo.supplier.modular.warehouse.stocks.service.SupplierStocksService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品信息Service接口实现类
 *
 * @author Mr.wu
 * @date  2025/03/15 10:46
 **/
@Service
public class SupplierProductionsServiceImpl extends ServiceImpl<SupplierProductionsMapper, SupplierProductions> implements SupplierProductionsService {
    @Resource
    private SupplierCategoriesService supplierCategoriesService;

    @Resource
    private SupplierStocksService supplierStocksService;

    @Resource
    private TransService transService;


    @Override
    public Page<SupplierProductions> page(SupplierProductionsPageParam supplierProductionsPageParam) {
        QueryWrapper<SupplierProductions> queryWrapper = new QueryWrapper<SupplierProductions>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionCode())) {
            queryWrapper.lambda().like(SupplierProductions::getProductionCode, supplierProductionsPageParam.getProductionCode());
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionBarcode())) {
            queryWrapper.lambda().like(SupplierProductions::getProductionBarcode, supplierProductionsPageParam.getProductionBarcode());
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionName())) {
            queryWrapper.lambda().like(SupplierProductions::getProductionName, supplierProductionsPageParam.getProductionName());
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionPinyincode())) {
            queryWrapper.lambda().eq(SupplierProductions::getProductionPinyincode, supplierProductionsPageParam.getProductionPinyincode());
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionBrand())) {
            queryWrapper.lambda().eq(SupplierProductions::getProductionBrand, supplierProductionsPageParam.getProductionBrand());
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionCategoriesId())) {
            List<String> childCategoriesIdList = CollStreamUtil.toList(supplierCategoriesService.getChildListById(supplierCategoriesService
                    .getAllCategoriesList(), supplierProductionsPageParam.getProductionCategoriesId(), true), SupplierCategories::getId);
            if (ObjectUtil.isNotEmpty(childCategoriesIdList)) {
                queryWrapper.lambda().in(SupplierProductions::getProductionCategoriesId, childCategoriesIdList);
            } else {
                return new Page<>();
            }
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionSupplierMain())) {
            queryWrapper.lambda().eq(SupplierProductions::getProductionSupplierMain, supplierProductionsPageParam.getProductionSupplierMain());
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionSupplierList())) {
            queryWrapper.lambda().eq(SupplierProductions::getProductionSupplierList, supplierProductionsPageParam.getProductionSupplierList());
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getFilterSupplier()) && supplierProductionsPageParam.getFilterSupplier()) {
            queryWrapper.lambda().and(i->i.eq(SupplierProductions::getProductionSupplierMain,supplierProductionsPageParam.getProductionSupplier())
                    .or().apply("FIND_IN_SET(production_supplier_list,'" + supplierProductionsPageParam.getProductionSupplier() + "')"));
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getSearchKey())){
            queryWrapper.lambda().and(i->i.like(SupplierProductions::getProductionName,supplierProductionsPageParam.getSearchKey())
                    .or().like(SupplierProductions::getProductionPinyincode,supplierProductionsPageParam.getSearchKey())
                    .or().like(SupplierProductions::getProductionCode,supplierProductionsPageParam.getSearchKey())
                    .or().like(SupplierProductions::getProductionBarcode,supplierProductionsPageParam.getSearchKey()));
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionTag())) {
            queryWrapper.lambda().eq(SupplierProductions::getProductionTag, supplierProductionsPageParam.getProductionTag());
        }
        //如果带门店参数，则仅显示门店已有商品
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionStore())) {
            List<String> productionIds = CollStreamUtil.toList(supplierStocksService.list(new LambdaQueryWrapper<SupplierStocks>().eq(SupplierStocks::getStockStoreId,supplierProductionsPageParam.getProductionStore()).eq(SupplierStocks::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId())),SupplierStocks::getStockProductionId);
            if (ObjectUtil.isNotEmpty(productionIds)) {
                queryWrapper.lambda().in(SupplierProductions::getId,productionIds);
            }else{
                return new Page<>();
            }
        }
        //如查带仓库参数，则仅显示仓库已有商品
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionStorage())){
            List<String> productionIds = CollStreamUtil.toList(supplierStocksService.list(new LambdaQueryWrapper<SupplierStocks>().eq(SupplierStocks::getStockStorageId,supplierProductionsPageParam.getProductionStorage()).eq(SupplierStocks::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId())),SupplierStocks::getStockProductionId);
            if (ObjectUtil.isNotEmpty(productionIds)) {
                queryWrapper.lambda().in(SupplierProductions::getId,productionIds);
            }else{
                return new Page<>();
            }
        }
        //数据归属
        queryWrapper.lambda().eq(SupplierProductions::getCompanyId, StpLoginUserUtil.getLoginUser().getCompanyId());
        if(ObjectUtil.isAllNotEmpty(supplierProductionsPageParam.getSortField(), supplierProductionsPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(supplierProductionsPageParam.getSortOrder());
            queryWrapper.orderBy(true, supplierProductionsPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(supplierProductionsPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SupplierProductions::getSortCode);
        }
        if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getProductionStatus())){
            queryWrapper.lambda().eq(SupplierProductions::getProductionStatus,supplierProductionsPageParam.getProductionStatus());
        }

        Page<SupplierProductions> supplierProductionsPage = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        //在这里加入库位信息
        if(supplierProductionsPage.getTotal()>0){
            List<String> productionIds = CollStreamUtil.toList(this.page(CommonPageRequest.defaultPage(), queryWrapper).getRecords(), SupplierProductions::getId);
            List<SupplierStocks> stocksList = new ArrayList<>();
            if(ObjectUtil.isNotEmpty(supplierProductionsPageParam.getLocationStorage())) {
                //带仓库信息，只仅显示该商品在该仓库的库位信息
                stocksList = supplierStocksService.list(new QueryWrapper<SupplierStocks>().select("STOCK_PRODUCTION_ID,STOCK_STORE_LOCATION").groupBy("STOCK_PRODUCTION_ID,STOCK_STORE_LOCATION").lambda().eq(SupplierStocks::getStockStorageId,supplierProductionsPageParam.getLocationStorage()).in(SupplierStocks::getStockProductionId,productionIds));
            }else{
                stocksList = supplierStocksService.list(new QueryWrapper<SupplierStocks>().select("STOCK_PRODUCTION_ID,STOCK_STORE_LOCATION").groupBy("STOCK_PRODUCTION_ID,STOCK_STORE_LOCATION").lambda().in(SupplierStocks::getStockProductionId,productionIds));
            }
            if(ObjectUtil.isNotEmpty(stocksList)){
                transService.transBatch(stocksList);
                for(SupplierProductions supplierProductions : supplierProductionsPage.getRecords()){
                    List<String> locationIds = CollStreamUtil.toList(stocksList.stream().filter(item -> item.getStockProductionId().equals(supplierProductions.getId())).collect(Collectors.toList()), SupplierStocks::getStockStoreLocation);
                    List<String> locationNames = CollStreamUtil.toList(stocksList.stream().filter(item -> item.getStockProductionId().equals(supplierProductions.getId())).collect(Collectors.toList()), SupplierStocks::getStockStoreLocationName);
                    if(ObjectUtil.isNotEmpty(locationIds)){
                        supplierProductions.setProductionLocationIds(locationIds);
                        supplierProductions.setProductionLocationNames(locationNames);
                    }
                }
            }
        }
        return supplierProductionsPage;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SupplierProductionsAddParam supplierProductionsAddParam) {
        SupplierProductions supplierProductions = BeanUtil.toBean(supplierProductionsAddParam, SupplierProductions.class);
        //数据归属
        supplierProductions.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        this.save(supplierProductions);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SupplierProductionsEditParam supplierProductionsEditParam) {
        SupplierProductions supplierProductions = this.queryEntity(supplierProductionsEditParam.getId());
        BeanUtil.copyProperties(supplierProductionsEditParam, supplierProductions);
        this.updateById(supplierProductions);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SupplierProductionsIdParam> supplierProductionsIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(supplierProductionsIdParamList, SupplierProductionsIdParam::getId));
    }

    @Override
    public SupplierProductions detail(SupplierProductionsIdParam supplierProductionsIdParam) {
        return this.queryEntity(supplierProductionsIdParam.getId());
    }

    @Override
    public SupplierProductions queryEntity(String id) {
        SupplierProductions supplierProductions = this.getById(id);
        if(ObjectUtil.isEmpty(supplierProductions)) {
            throw new CommonException("商品信息不存在，id值为：{}", id);
        }
        return supplierProductions;
    }
}
